package com.sq.partner.manager.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 合作伙伴机构配置
 * @author Kang Zhiqiang 
 *
 */
@Controller
@RequestMapping("/subChannelConfig")
public class SubChannelConfigController {

	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	/**
	 * 进入subChannelConfig.jsp跳转操作
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/subChannelConfig")
	public String subChannelConfig() throws Exception{
		return "appManage/subChannelConfig";
	}
	
	/**
	 * 根据subChannelCode或subChannelName模糊查询subChannel
	 * @param session
	 * @param pageIndex
	 * @param channelCode
	 * @param channelName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/querySubChannelByFuzzyCriteria")
	@ResponseBody
	public Page querySubChannelByFuzzyCriteria(HttpSession session, Integer pageIndex, String subChannelCode,String subChannelName) throws Exception{
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		
		GatewaySubChannel subChannel = new GatewaySubChannel();
		subChannel.setSubChannelCode(subChannelCode);
		subChannel.setSubChannelName(subChannelName);
		//总行和分行
		boolean isHQFlag = false;
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			isHQFlag = user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
		}
		user.setHQFlag(isHQFlag);
		Page channelInfoPage = subChannelService.querySubChannelByFuzzyCriteria(pageIndex, subChannel, user);
		
		return channelInfoPage;
	}
	
	/**
	 * 加载当前用户的权限机构及其子机构对应的合作伙伴及其合作伙伴机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelTree")
	@ResponseBody
	public Page<GatewaySubChannel> queryChannelTree(HttpSession session, Integer size,int pageIndex,GatewaySubChannel subChannel) throws Exception{
		Page<GatewaySubChannel> page = new Page<GatewaySubChannel>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		page.setType(subChannel);
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//总行和分行
		boolean isHQFlag = false;
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			isHQFlag = user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
		}
		user.setHQFlag(isHQFlag);
		
 		page = subChannelService.queryChannelTreeByOneUser(user,page);
		
		return page;
	}
	
	@RequestMapping("/saveSubChannel")
	@ResponseBody
	public Result saveSubChannel(HttpSession session,String subChannelCode,String subChannelName,String parentChannelCode,String flag) throws Exception{
		if(StrUtil.isEmpty(flag)){
			return Result.error("系统错误");
		}else if(StrUtil.isEmpty(parentChannelCode)){
			return Result.error("系统错误");
		}
		GatewaySubChannel tem = subChannelService.querySubChannelInfoById(parentChannelCode);
		if(null != tem && StrUtil.isNotEmpty(tem.getFkChannelCode())){
			GatewayChannelInfo resultData = channelInfoConfigService.queryChannelInfoByChannelCode(tem.getFkChannelCode());
			if (null != resultData && StrUtil.isNotEmpty(resultData.getDeptCode())) {
				if (!(channelInfoConfigService.checkIsHasPrivilege(session,resultData.getDeptCode()))) {
					return Result.error("权限不足，无权操作该合作伙伴!");
				}
			}else
			{
				return Result.error("权限不足，无权操作该合作伙伴!");
			}
		}else{
			return Result.error("上级合作伙伴机构代码系统不存在，操作失败！");
		}
	    if(StrUtil.isEmpty(subChannelCode)){
			return Result.error("合作伙伴机构代码不能为空");
		}else if(!subChannelCode.matches("^[a-zA-Z_0-9]{1,30}$")){
			return Result.error("合作伙伴机构代码只支持字母数字下划线组合且长度不能大于30");
		}else if(StrUtil.isEmpty(subChannelName)){
			return Result.error("合作伙伴机构名称不能为空");
		}
		
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Long operUser = user.getUserid();
		Date operTime = new Date();
		String status = "1";
		
		GatewaySubChannel subChannel = new GatewaySubChannel(subChannelCode, subChannelName, parentChannelCode, status, operUser, operTime);
		subChannel.setFkChannelCode(tem.getFkChannelCode());
		if("save".equalsIgnoreCase(flag))
		{
			GatewaySubChannel checkPk = subChannelService.querySubChannelInfoById(subChannel.getSubChannelCode());
			if(null!= checkPk){
				return Result.error("该合作伙伴机构代码已经占用，请修改后再次保存！");
			}
		}
		boolean res = subChannelService.saveOrUpdateSubChannel(subChannel, flag);
		
		if(res){
			if(flag.equals("save")){
				return Result.success("添加成功");
			}
			if(flag.equals("update")){
				return Result.success("修改成功");
			}
		}else{
			if(flag.equals("save")){
				return Result.error("添加失败");
			}
			if(flag.equals("update")){
				return Result.error("修改失败");
			}
		}
		return Result.error("系统错误");
	}
	
	/**虚拟删除
	 * 根据subChannelCode虚拟删除相应的subChannel
	 * @param session
	 * @param subChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delSubChannelBySubChannelCode")
	@ResponseBody
	public Result delSubChannelBySubChannelCode(HttpSession session,String subChannelCode ,String deptCode, String parentChannelCode) throws Exception{
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}else if(StrUtil.isEmpty(subChannelCode)){
			return Result.error("操作失败，合作伙伴机构代码不能为空！");
		}else if(StrUtil.isEmpty(parentChannelCode)){
			return Result.error("顶级机构不允许删除，当删除顶级机构关联的合作伙伴时系统自动删除！");
		}
		//先查询该subChannelCode对应的subChannel是否有下级subChannel(status = '1')
		GatewaySubChannel sc = new GatewaySubChannel();
		sc.setParentChannelCode(subChannelCode);
		sc.setStatus("1");
		List<GatewaySubChannel> subChannelList = subChannelService.querySubChannelListBySubChannel(sc);
		if(subChannelList.size() > 0){
			return Result.error("该机构下关联有下级机构，请先删除下级机构");
		}
		
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Long operUser = user.getUserid();
		Date operTime = new Date();
		String status = "0";
		
//		subChannel.setStatus(status);
//		subChannel.setOperUser(operUser);
//		subChannel.setOperTime(operTime);
		
		boolean res = subChannelService.delSubChannel(subChannelCode);//此方法由虚拟删除已改为物理删除
		
		if(res){
			return Result.success("删除成功");
		}else{
			return Result.error("删除失败");
		}
	}
}
